package com.bosssoft.trainee.nontax.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bosssoft.trainee.nontax.dao.UserMapper;
import com.bosssoft.trainee.nontax.entity.dto.RoleDTO;
import com.bosssoft.trainee.nontax.entity.po.RolePO;
import com.bosssoft.trainee.nontax.dao.RoleMapper;
import com.bosssoft.trainee.nontax.entity.po.UserPO;
import com.bosssoft.trainee.nontax.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sct
 * @since 2022-06-15
 */
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RolePO> implements RoleService {

    @Resource
    private UserMapper userMapper;

    @Override
    public IPage<RolePO> findRoleListByUserId(IPage<RolePO> page, RoleDTO roleDTO) {
        QueryWrapper<RolePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!ObjectUtils.isEmpty(roleDTO.getRoleName()),"role_name",roleDTO.getRoleName());
        queryWrapper.orderByAsc("id");
        UserPO userPO = userMapper.selectById(roleDTO.getUserId());
        //如果用户不为空、且不是管理员，则只能查询自己创建的角色
        if(userPO !=null && !ObjectUtils.isEmpty(userPO.getIsAdmin()) && userPO.getIsAdmin()!=1){
            queryWrapper.eq("create_user",roleDTO.getUserId());
        }
        return baseMapper.selectPage(page,queryWrapper);
    }

    @Override
    public boolean hasRoleCount(Long id) {
        return baseMapper.getRoleCountByRoleId(id)>0;
    }

    @Override
    public boolean deleteRoleById(Long id) {
        //删除角色权限关系
        baseMapper.deleteRolePermissionByRoleId(id);
        return baseMapper.deleteById(id)>0;
    }

    /**
     * 保存角色权限关系
     * @param roleId
     * @param permissionIds
     * @return
     */
    @Override
    public boolean saveRolePermission(Long roleId, List<Long> permissionIds) {
        baseMapper.deleteRolePermission(roleId);
        return baseMapper.saveRolePermission(roleId,permissionIds)>0;
    }

    /**
     * 根据用户ID查询该用户拥有的角色ID
     * @param userId
     * @return
     */
    @Override
    public List<Long> findRoleIdByUserId(Long userId) {
        return baseMapper.findRoleIdByUserId(userId);
    }
}
